package iaccounts

import (
	"context"
	"crypto/tls"
	"fmt"
	"net/http"

	"gitee.com/djaf/my-certs/app/classes/accounts"
	"gitee.com/djaf/my-certs/app/data/dxo"
	"gitee.com/djaf/my-certs/app/web/dto"

	"github.com/mholt/acmez"
	"github.com/mholt/acmez/acme"
	"go.uber.org/zap"
)

type accountSignUpTask struct {

	// input

	context    context.Context
	service    *ServiceImpl
	serviceAPI accounts.Service
	accountID  dxo.AccountID

	// temp

	accountDTO *dto.Account
}

func (inst *accountSignUpTask) run() error {

	ctx := inst.context
	id := inst.accountID
	accountItem, err := inst.serviceAPI.Find(ctx, id)
	if err != nil {
		return err
	}

	keyID := accountItem.KeyPair
	privateKey, err := inst.service.KeyPairService.LoadSigner(ctx, keyID)
	if err != nil {
		return err
	}

	logger, err := zap.NewDevelopment()
	if err != nil {
		return err
	}

	// send
	url := accountItem.ServiceURL
	skipVerify := accountItem.DebugMode

	client := acmez.Client{
		Client: &acme.Client{
			Directory: url,
			HTTPClient: &http.Client{
				Transport: &http.Transport{
					TLSClientConfig: &tls.Config{
						InsecureSkipVerify: skipVerify,
					},
				},
			},
			Logger: logger,
		},
	}

	email := accountItem.Email
	account := acme.Account{
		Contact:              []string{"mailto:" + email},
		TermsOfServiceAgreed: true,
		PrivateKey:           privateKey,
	}

	account, err = client.NewAccount(ctx, account)
	if err != nil {
		return fmt.Errorf("new account: %v", err)
	}
	return nil
}
